import React, {Component} from 'react';
import './index.less';
import {getMetaKey, base, high} from 'nc-lightapp-front';
import Header from '../components/Header';
import LeftTree from '../components/LeftTree';
import SearchModal from '../components/SearchModal';
import getMainTableData from './functions/getMainTableData';
import cleanMainTableData from './functions/cleanMainTableData';
import getSysConf from './functions/getSysConf';
import MainTable from '../components/MainTable';
import SortModal from '../components/SortModal';
import toggleModal from './functions/toggleModalVisible';
import processTemplate from './functions/processTemplateData';
import ShowType from '../components/ShowType';
import updateButtonStatus from './functions/updateButtonStatus';
import Detail from '../components/Detail';
import RosterModal from '../../../../public/components/RosterModal';
import DragHeightCom from '../../../../public/components/DragHeightCom';
import ReptObjModal from '../components/ReptObjModal';
import JobHisModal from '../components/JobHisModal';
import ExportModal from '../components/ExportModal';
import Uploader from '../components/Uploader';
//import viewCard from './functions/viewCard';
import SubSetCard from '../../../../infomaintenance/psninfomaintenance/components/SubSetTableCard';
import ins from '../instance';
import ViewCard from 'src/hrpub/common/components/card-view';
import WpsModal from 'src/hrpub/common/components/wpsPreModel';
import {getAppPageConfig, handleHash} from "../../../../../hrpub/common/utils/utils";

//@handleHash('20198162232323', '/ifr?page=20198162232323&c=60071030&p=60071030p&ar=0001Z700APPN60071030')

class EntryStaffQuery extends Component {
    constructor(props) {
        super(props);
        if (props.use) {
            props.use.search('ncc60071702query');
            props.use.table('ncc60071702list', 'hi_psnjob_history', 'hi_psnjob_history_down');
            props.use.editTable('sort');
            props.use.form('bd_psndoc', 'hi_psnorg_h', 'hi_psnjob_h');
            props.use.cardTable(...props.cardTableList);
            //props.use.editTable(...props.cardTableList);
        }
        this.config = getAppPageConfig();
        this.state = {
            page: 'main',
            orgVal: {},
            json: {},
            treeType: 'adminOrg',
            searchModalValue: {},
            queryOid: '',
            pageInfo: {
                pageSize: 10,
                pageIndex: 1,
                total: 0,
                totalPage: 1
            },
            sortModalVisible: false,
            rosterModalVisible: false,
            hasSearched: false,
            include_child_depts: true, //是否包含下级部门人员
            include_child_orgs: false, //是否包含下级组织人员
            include_child_psncl: false, //包含下级人员类别人员
            show_all_info: false, //显示历史人员
            show_on_job_psn: true, //在职人员
            currentSelectTreeNode: '',
            detailTemplate: {},
            reptObjVisible: false,
            reptColumns: [],
            reptData: [],
            exportFilter: [],
            exportType: '',
            exportAllpks: [],
            rosterPks: '', //需要联查花名册的人员pks,
            showUploader: false,
            showHistoryTable: false,
            subsetVisible: false, // 是否显示子集
            pageHeight: 0, // 页面高度
            showSubsetDisabled: true, //  是否禁用显示子集复选框
            subsetCardChecked: false, // 是否显示自己的复选框
            focusedRow: null,
            isShowBottomDom: false,
            subHeight: 0
        };
        props.MultiInit.getMultiLang({
            moduleId: 'hi6007',
            domainName: 'hrhi',
            callback: (json, status, inlt) => {
                if (status) {
                    this.setState({json, inlt}); //存json和inlt到页面state中并刷新页面
                }
                //props.createUIDom(this.config, (data) => {
                let data = props.templateData;
                this.setState({
                    buttons: data.button || [],
                    context: data.context || {},
                    queryOid: data.template.ncc60071702query.oid
                });

                data.template = processTemplate.call(this, data.template);

                props.meta.setMeta(data && data.template ? data.template : {});
                props.button.setButtons(data && data.button ? data.button : {});
                updateButtonStatus.call(this);
                //});
                this.getPageHeight();
                // 此版本与05版本的要挂在search上，不是myState上，并且keySessionS为数组类型。
                let keySessionS = getMetaKey(this.config.appcode, this.config.pagecode);
                ins.ins.myState.search.keySessionS = [keySessionS];
            }
        });


        this.cIns = {
            subSetCard: null
        };

        this.updateState = this.updateState.bind(this);
        this.getMainTableData = this.getMainTableData.bind(this);
        this.cleanMainTableData = this.cleanMainTableData.bind(this);
        this.toggleModal = this.toggleModal.bind(this);
        this.sortModalOnSure = this.sortModalOnSure.bind(this);
        this.selectTree = this.selectTree.bind(this);
        this.updateOrgValue = this.updateOrgValue.bind(this);
        this.goBackToMainPage = this.goBackToMainPage.bind(this);
        this.viewCard = this.viewCard.bind(this);
        this.getPageHeight = this.getPageHeight.bind(this);
        this.getSysConf = this.getSysConf.bind(this);
        this.onDragStop = this.onDragStop.bind(this)
    }

    componentDidMount() {
        //if (window.location.href.match('localhost:3006')) window.location.hash = `#/ifr?page=20198162232323`;
    }

    // 获取app高度
    getPageHeight() {
        if (window.getComputedStyle) {
            let height = window.getComputedStyle(document.getElementById('app')).height.replace('px', '');

            this.setState({
                pageHeight: height
            });
        }
    }

    async updateOrgValue(value) {
        await this.getSysConf(value);
        this.setState(
            {
                orgVal: value,
                currentSelectTreeNode: ''
            },
            () => {
                if (this.state.hasSearched) {
                    //this.cleanMainTableData();
                    this.getMainTableData();
                } else {
                    updateButtonStatus.call(this);
                }
            }
        );
    }

    getSysConf = (orgValue) => {
        return getSysConf.call(this, orgValue);
    };

    updateState(data, callback = () => {
    }) {
        this.setState(data, callback);
    }

    getMainTableData() {
        getMainTableData.call(this);
    }

    cleanMainTableData() {
        cleanMainTableData.call(this);
    }

    // 切换各种弹窗显示隐藏，type为弹窗的显示隐藏state的key值
    toggleModal(type, visible) {
        return toggleModal.call(this, type, visible);
    }

    // 排序弹窗点击确定的回调
    sortModalOnSure() {
        const {pageInfo, hasSearched} = this.state;
        if (hasSearched) {
            this.setState(
                {
                    pageInfo: {
                        ...pageInfo,
                        pageIndex: 1
                    }
                },
                () => {
                    this.getMainTableData();
                }
            );
        }
    }

    //左侧树节点选择回调
    selectTree(pk) {
        const {pageInfo, hasSearched} = this.state;
        this.setState(
            {
                currentSelectTreeNode: pk,
                pageInfo: {
                    ...pageInfo,
                    pageIndex: 1,
                    total: 0,
                    totalPage: 1
                }
            },
            () => {
                if (hasSearched) {
                    this.getMainTableData();
                }
            }
        );
    }

    goBackToMainPage() {
        this.setState(
            {
                page: 'main'
            },
            () => {
                updateButtonStatus.call(this);

                let insMyTable = ins.ins.myTable;

                ins.ins.myTable = {
                    json: insMyTable.json,
                    myEditTable: insMyTable.myEditTable,
                    ncc60071702list: insMyTable['ncc60071702list']
                };

                if (this.state.subsetVisible) {
                    this.setState({
                        isShowBottomDom: true
                    })
                    setTimeout(() => {
                        this.cIns.subSetCard.initSubSet();
                    }, 1);
                }
            }
        );
    }

    viewCard() {
        //viewCard.call(this);
        // this.viewCardNode.openCardViewModal(this.props.table.getCheckedRows('ncc60071702list'));
        this.wpsview.openView(this.props.table.getCheckedRows('ncc60071702list'))
    }

    onDragStop(clientHei) {
        let pageHeight = window.getComputedStyle(document.getElementById('app')).height.replace('px', '');
        let hei = pageHeight - clientHei
        if (document.getElementsByClassName("dragHeightCom_top")) {
            document.getElementsByClassName("dragHeightCom_top")[0].style.height = hei + 'px'
            this.setState({
                subHeight: clientHei
            })
        }
    }

    render() {
        const {
            page,
            orgVal,
            treeType,
            queryOid,
            pageInfo,
            rosterModalVisible,
            json,
            showHistoryTable,
            sortModalVisible,
            include_child_depts,
            include_child_orgs,
            detailTemplate,
            rosterPks,
            include_child_psncl,
            show_all_info,
            show_on_job_psn,
            hasSearched,
            currentSelectTreeNode,
            reptObjVisible,
            reptColumns,
            reptData,
            exportFilter,
            exportAllpks,
            exportType,
            showUploader,
            subsetVisible,
            pageHeight,
            showSubsetDisabled,
            subsetCardChecked,
            focusedRow,
            isShowBottomDom,
            subHeight
        } = this.state;
        const {table, meta, editTable, DragWidthCom} = this.props;
        let topDom = <div
            className="psn-query-main nc-bill-card"
            style={{display: page === 'main' ? '' : 'none'}}
        >
            <Header
                {...this.props}
                json={json}
                page={page}
                getMainTableData={this.getMainTableData}
                orgVal={orgVal}
                hasSearched={hasSearched}
                treeType={treeType}
                pageInfo={pageInfo}
                include_child_depts={include_child_depts}
                include_child_orgs={include_child_orgs}
                include_child_psncl={include_child_psncl}
                show_all_info={show_all_info}
                show_on_job_psn={show_on_job_psn}
                updateState={this.updateState}
                viewCard={this.viewCard}
                updateOrgValue={this.updateOrgValue}
                cIns={this.cIns}
                showSubsetDisabled={showSubsetDisabled}
                subsetCardChecked={subsetCardChecked}
            />
            <div className="entry-staff-query-content">
            <DragWidthCom
            leftDom={
                <div
                    className="left-content"
                    style={{
                        height: !subsetVisible ? `${pageHeight - 46}px` : '100%'//`${pageHeight * 0.7 - 46}px`
                    }}
                >
                    <ShowType
                        json={json}
                        pageInfo={pageInfo}
                        hasSearched={hasSearched}
                        treeType={treeType}
                        updateState={this.updateState}
                        getMainTableData={this.getMainTableData}
                    />
                    <LeftTree
                        {...this.props}
                        json={json}
                        treeType={treeType}
                        asyncTree={this.props.asyncTree}
                        onSelect={this.selectTree}
                        pk_org={orgVal.refpk}
                        treeId="departmentTree"
                        subHeight={subHeight}
                    />
                </div>
            }
            rightDom={
                <div className="right-content">
                    <MainTable
                        {...this.props}
                        json={json}
                        orgVal={orgVal}
                        updateState={this.updateState}
                        getMainTableData={this.getMainTableData}
                        pageInfo={pageInfo}
                        pageHeight={pageHeight}
                        cIns={this.cIns}
                        subsetVisible={subsetVisible}
                        focusedRow={focusedRow}
                        subHeight={subHeight}
                    />
                </div>
            }
            defLeftWid='20%'    // 默认左侧区域宽度，px/百分百
            leftMinWid='180px'
            />


            </div>
        </div>

        let bottomDom = <div>
            {page === 'main' && subsetVisible && <SubSetCard
                {...this.props}
                visible={subsetVisible}
                ref={ref => this.cIns.subSetCard = ref}
                orgVal={orgVal}
                mainTableId="ncc60071702list"
                pageHeight={pageHeight}
                func_type={'3'}
                subHeight={subHeight}
            />}
        </div>
        return (
            <div>
                <div
                    className="entry-staff-query"
                    style={{
                        height: page !== 'main' ? 'auto' : (page === 'main' && subsetVisible) ? '100%' : `${pageHeight}px`
                    }}
                >
                    {page === 'main' && <DragHeightCom
                        topDom={topDom}
                        bottomDom={bottomDom}
                        isShowBottomDom={isShowBottomDom}
                        defBottomHei='auto'
                        onDragStop={this.onDragStop}
                    />}
                    {page === 'main' ? null : (
                        <Detail
                            orgVal={orgVal}
                            json={json}
                            exportAllpks={exportAllpks}
                            {...this.props}
                            detailTemplate={detailTemplate}
                            updateState={this.updateState}
                            goBackToMainPage={this.goBackToMainPage}
                        />
                    )}
                    <SearchModal
                        {...this.props}
                        json={json}
                        pageInfo={pageInfo}
                        queryOid={queryOid}
                        updateState={this.updateState}
                        getMainTableData={this.getMainTableData}
                    />

                    <SortModal
                        editTable={editTable}
                        meta={meta}
                        json={json}
                        visible={sortModalVisible}
                        onSure={this.sortModalOnSure}
                        onClose={this.toggleModal('sortModalVisible', false)}
                        templateId="sort"
                    />

                    <RosterModal
                        {...this.props}
                        json={json}
                        orgVal={orgVal}
                        queryOid={queryOid}
                        tree_node_id={currentSelectTreeNode}
                        include_child_depts={include_child_depts}
                        include_child_orgs={include_child_orgs}
                        include_child_psncl={include_child_psncl}
                        show_all_info={show_all_info}
                        show_on_job_psn={show_on_job_psn}
                        func_type={3}
                        visible={rosterModalVisible}
                        onClose={this.toggleModal('rosterModalVisible', false)}
                        rosterPks={rosterPks}
                    />

                    <ReptObjModal
                        json={json}
                        visible={reptObjVisible}
                        columns={reptColumns}
                        data={reptData}
                        onClose={this.toggleModal('reptObjVisible', false)}
                    />

                    <JobHisModal {...this.props} json={json} showHistoryTable={showHistoryTable}/>

                    <ExportModal
                        {...this.props}
                        json={json}
                        orgVal={orgVal}
                        show_on_job_psn={show_on_job_psn}
                        exportType={exportType}
                        exportFilter={exportFilter}
                        exportAllpks={exportAllpks}
                    />

                    <ViewCard
                        {...this.props}
                        onRef={
                            node => this.viewCardNode = node
                        }
                    />
                    <WpsModal
                        {...this.props}
                        onRef ={node => this.wpsview = node}
                        appcode={'60071030'}
                        pk_org={orgVal}

                    />
                    {showUploader && <Uploader
                        json={json}
                        table={table}
                        onClose={this.toggleModal('showUploader', false)}/>}
                </div>
            </div>
        );
    }
}

export default EntryStaffQuery;
